<template>
  <div>
    <uploader :options="options" :file-status-text="statusText" class="uploader-example" :auto-start="true" @file-complete="fileComplete" @complete="complete">
      <uploader-unsupport />
      <uploader-drop v-show="!uploadReadonly">
        <uploader-btn ref="uploader">从本地上传</uploader-btn>
        <label v-if="dataArchive" class="uploader-btn" @click="getHasFile">选择已有文件</label>
        <!-- <uploader-btn ref="uploader" :directory="true">选择文件夹</uploader-btn> -->
        <p>将文件拖拽到此</p>
      </uploader-drop>
      <uploader-list />
      <div v-for="item in fileList" :key="item.guid || item.fileId " class="myfileList">
        <span class="fileName">{{ item.fileName }}</span>
        <span v-show="!uploadReadonly" class="myfileList-remove" @click="removeFileList(item.guid||item.fileId)">
          <i class="el-icon-close" style=" font-weight: 600;  text-align: center" />
        </span>
        <span class="myfileList-preview" @click="handlePreview(item)">
          <a style=" text-align: center">
            <i class="el-icon-search acion"/> 预览
          </a>
        </span>
      </div>
    </uploader>
  </div>
</template>

<script>
import axios from 'axios';
import qs from 'qs';
import { getToken } from '@/utils/auth';
import { Loading } from 'element-ui';
// import uploader from 'vue-simple-uploader';

export default {
  name: 'VueUploader',
  // components: {
  //   uploader
  // },
  props: {
    dataArchive: {
      type: Boolean,
      default: false
    },
    singleType: {
      type: Boolean,
      default: true
    },
    fileList: {
      type: Array,
      default: () => []
    },
    uploadReadonly: {
      type: Boolean,
      default: false
    },
    pathName: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      loading: null,
      datetime: null,
      options: {
        target: process.env.VUE_APP_BASE_API + '/api/system/uploader/chunk',
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        testChunks: true,
        simultaneousUploads: 3,
        chunkSize: 5 * 1024 * 1024,
        singleFile: this.singleType,
        // uploadMethod: (aa) => {
        //   console.log(aa);
        // }

        generateUniqueIdentifier: val => {
          this.datetime = Date.parse(new Date())

          return this.datetime + val.size
        },
        checkChunkUploadedByResponse: function(chunk, message) {
          console.log(message)
          var objMessage = {}
          try {
            objMessage = JSON.parse(message)
          } catch (e) {}
          // fake response
          // objMessage.uploaded_chunks = [2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 17, 20, 21]
          // check the chunk is uploaded
          return (
            (objMessage.uploaded_chunks || []).indexOf(chunk.offset + 1) >= 0
          )
        }
      },
      attrs: {
        accept: 'image/*'
      },
      statusText: {
        success: '成功了',
        error: '出错了',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      window.uploader = this.$refs.uploader.uploader
    })
  },

  methods: {
    getHasFile() {
      this.$emit('getHasFile', true)
    },
    // 上传完成
    complete() {
      console.log('complete', arguments)
    },
    // 一个根文件（文件夹）成功上传完成。
    fileComplete() {
      debugger
      var that = this
      console.log('file complete', arguments)
      if (arguments[0].chunks[0].processedState.res !== '文件上传成功') {
        this.msgError(arguments[0].chunks[0].processedState.res)
        return false
      }
      const file = arguments[0].file
      // file.cancel()
      const formData = new FormData()
      formData.append('filename', file.name)
      formData.append('identifier', this.datetime + arguments[0].size)
      formData.append('totalSize', file.size)
      formData.append('type', file.type)
      formData.append('cover', false)
      formData.append('path', this.pathName)

      axios
        .post(
          process.env.VUE_APP_BASE_API + '/api/system/uploader/getMergeFileId',
          formData,
          {
            headers: {
              Authorization: 'Bearer ' + getToken()
            }
          }
        )
        .then(function(response) {
          that.$emit('changeFileData', response.data, file.name);
          that.fileCompleteSec(formData);
          
          

        })
        .catch(function(error) {
          // console.log(error)
        })



      
    },
    fileCompleteSec(formData){
      debugger
      axios
        .post(
          process.env.VUE_APP_BASE_API + '/api/system/uploader/mergeFile',
          formData,
          {
            headers: {
              Authorization: 'Bearer ' + getToken()
            }
          }
        )
        .then(function(response) {

        })
        .catch(function(error) {
          // console.log(error)
        })
    },
    removeFileList(id) {
      this.$emit('removeFileList', id)
    },
    handlePreview(row) {
      this.filePreview(row.fileName, row.storagePath)
    }
  }
}
</script>

<style>
.uploader-example {
  width: 100%;
  /* padding: 15px; */
  /* margin: 40px auto 0; */
  font-size: 12px;
  /* box-shadow: 0 0 10px rgba(62, 146, 203, 0.4); */
}

.uploader-example .uploader-btn {
  margin-right: 4px;
}

.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
.uploader-btn {
  border-color: #dcdfe6 !important;
  padding: 12px 20px !important;
  background: #fff !important;
  border-radius: 4px !important;
  font-size: 14px !important;
  line-height: 1 !important;
}
.uploader-file[status="success"] .uploader-file-remove {
  display: block !important;
}
.uploader-file-icon:before {
  display: none !important;
}
.uploader-file-icon {
  width: 0 !important;
  margin-right: 0 !important;
}
.myfileList {
  text-indent: 14px;
  border-bottom: 1px solid #cdcdcd;
  background-color: #e2eeff;
  height: 46px;
  line-height: 46px;
  display: flex;
}
.fileName {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: keep-all;
  flex: 1;
}
.myfileList-remove {
  /* margin-top: 16px; */
  text-indent: 0px;
  float: right;
  font-size: 16px;
  cursor: pointer;
  width: 10%;
}
.myfileList-preview {
  /* margin-top: 16px; */
  text-indent: 0px;
  float: right;
  font-size: 14px;
  cursor: pointer;
  width: 60px;
}
</style>
